<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      label-position="right"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('page_sys.user.labelYhzh')" prop="username">
            <el-input
              v-model="formData.username"
              :placeholder="t('page_sys.user.placeholderYhzh')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('page_sys.user.labelNickname')" prop="nickname">
            <el-input
              v-model="formData.nickname"
              :placeholder="t('page_sys.user.placeholderYhnc')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('page_sys.user.labelSszz')" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              check-strictly="true"
              :placeholder="t('common.selectText')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('page_sys.user.labelSjh')" prop="mobile">
            <el-input
              v-model="formData.mobile"
              maxlength="11"
              :placeholder="t('page_sys.user.placeholderSjh')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('page_sys.user.labelEmail')" prop="email">
            <el-input
              v-model="formData.email"
              maxlength="50"
              :placeholder="t('page_sys.user.placeholderEmail')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item
            v-if="formData.id === undefined"
            :label="t('page_sys.user.labelPwd')"
            prop="password"
          >
            <el-input
              v-model="formData.password"
              :placeholder="t('page_sys.user.placeholderPwd')"
              show-password
              type="password"
              autocomplete="new-password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('page_sys.user.labelSex')" prop="sex">
            <el-select v-model="formData.sex" :placeholder="t('page_sys.user.placeholderSex')">
              <el-option :value="0" :label="t('page_sys.user.placeholderSex')" />
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="t('page_sys.user.labelAvatar')">
            <UploadImg
              class="avatar-uploader"
              v-model="formData.avatar"
              height="80px"
              width="80px"
              :data="{ type: 'other' }"
            >
              <template #empty>
                <div class="upload-btn-container">
                  <Icon
                    class="avatar-uploader-icon"
                    icon="ep:plus"
                    :size="18"
                    style="margin-top: 16px"
                  />
                  <div style="margin-top: 2px">{{ t('cropper.selectImage') }}</div>
                </div>
              </template>
              <template #tip>
                <div class="el-upload__tip" style="line-height: 2; text-align: left">
                  {{ t('page_sys.user.placeholderAvatar') }}
                </div>
              </template>
            </UploadImg>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            :label="t('page_sys.user.labelRole')"
            prop="roleIds"
            class="role-select-container"
          >
            <el-select v-model="formData.roleIds" multiple :placeholder="t('common.selectText')">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">{{ t('action.cancel') }}</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{
        t('action.submit')
      }}</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import * as RoleApi from '@/api/system/role'
import { FormRules } from 'element-plus'
import { getAccessToken } from '@/utils/auth'
import type { UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const UPLOAD_URL =
  import.meta.env.VITE_BASE_URL + '/admin-api/biz/modularityUpload/project1723468275223970/upload'
const HEADERS = { Authorization: 'Bearer ' + getAccessToken() } // 设置上传的请求头部
defineOptions({ name: 'SystemUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  nickname: '',
  deptId: '',
  mobile: '',
  email: '',
  id: undefined,
  username: '',
  password: '',
  sex: undefined,
  postIds: [],
  remark: '',
  status: CommonStatusEnum.ENABLE,
  roleIds: [],
  avatar: ''
})

const formRules = reactive<FormRules>({
  username: [
    { required: true, message: t('page_sys.user.tipYhzh'), trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: '用户账号由数字、字母组成',
      trigger: 'blur'
    }
  ],
  nickname: [{ required: true, message: t('page_sys.user.tipYhnc'), trigger: 'blur' }],
  deptId: [{ required: true, message: t('page_sys.user.placeholderSszz'), trigger: 'change' }],
  password: [
    { required: true, message: t('page_sys.user.tipPwd'), trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{6,16}$/,
      message: '密码必须包含大小写字母、数字和符号，长度在6-16之间',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    {
      type: 'email',
      message: t('page_sys.user.tipEmail'),
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: t('page_sys.user.tipSjh'),
      trigger: 'blur'
    }
  ],
  sex: [{ required: true, message: t('page_sys.user.placeholderSex'), trigger: 'blur' }],
  roleIds: [{ required: true, message: t('page_sys.user.placeholderRole'), trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([] as PostApi.PostVO[]) // 岗位列表
const roleList = ref([] as RoleApi.RoleVO[]) // 角色的列表
const isAdminRole = ref(false) //唯一管理员角色
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await UserApi.getUser(id)
      formData.value = res
      // bugfixed: 无法获取 userRoles 列表
      if (res.userRoles) {
        formData.value.roleIds = res.userRoles.map((item: { id: number }) => item.id)
        const adminRoleInfo = res.userRoles.find((res) => res.code === 'tenant-admin')
        isAdminRole.value = adminRoleInfo && adminRoleInfo.id ? true : false
      }
    } finally {
      formLoading.value = false
    }
  }
  getDepartList()
  // 加载岗位列表
  postList.value = await PostApi.getSimplePostList()
  // 加载角色列表
  const queryRoleList = await RoleApi.getSimpleRoleList()
  roleList.value = queryRoleList.filter((res) => {
    if (id && isAdminRole.value) {
      return res.code == 'tenant-admin'
    } else {
      return !['tenant-admin', 'patrol-plan-admin', 'maintenance-scheme-admin'].includes(res.code)
    }
  })
  console.log('>>>>>>isAdminRole', isAdminRole.value)
  console.log('>>>>>>>roleList', roleList.value)
}

const getGroupListTrees = (data: any) => {
  if (Array.isArray(data)) {
    return data.map((item) => getGroupListTrees(item))
  } else if (typeof data === 'object' && data !== null) {
    const result: any = {}
    for (let key in data) {
      if (key === 'name') {
        result.label = data[key]
      } else if (key === 'id') {
        result.value = String(data[key])
      } else {
        result[key] = getGroupListTrees(data[key])
      }
    }
    return result
  } else {
    return data
  }
}
/** 查询部门列表 */
const getDepartList = async () => {
  const data = await DeptApi.getDeptTree()
  deptList.value = getGroupListTrees(data.tree)
}

// 上传用户头像
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // console.log('response :>> ', response);
  formData.value.avatar = response.data.url

  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  // console.log('imageUrl :>> ', imageUrl.value);
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const validTypes = ['image/jpeg', 'image/jpg', 'image/png']
  if (!validTypes.includes(rawFile.type)) {
    ElMessage.error(t('page_sys.user.tipImgType'))
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error(t('page_sys.user.tipImgSize'))
    return false
  }
  return true
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserApi.UserVO
    if (formType.value === 'create') {
      await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    deptId: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    password: '',
    sex: undefined,
    postIds: [],
    remark: '',
    status: CommonStatusEnum.ENABLE,
    roleIds: [],
    avatar: ''
  }
  formRef.value?.resetFields()
}
</script>
<style>
.avatar-uploader .el-upload {
  position: relative;
  width: 178px;
  height: 178px;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.upload-btn-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.avatar {
  display: block;
  width: 178px;
  height: 178px;
}
.role-select-container .el-select__wrapper {
  padding: 10px 20px;
}
</style>
